﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System;
public class ButtonClick
{
    private static Dictionary<Button, List<Action>> dicBtnAction = new Dictionary<Button, List<Action>>();

    public static void AddClickListener(Button btn,Action callback)
    {
        if(dicBtnAction.ContainsKey(btn))
        {
            List<Action> actioList = dicBtnAction[btn];
            actioList.Add(callback);
        }
        else
        {
            List<Action> actionList = new List<Action>();
            actionList.Add(callback);
            btn.onClick.AddListener(() =>
            {
                if (dicBtnAction.ContainsKey(btn))
                {
                    List<Action> callbacks = dicBtnAction[btn];
                    for (int i = 0; i < callbacks.Count; i++)
                    {
                        Action action = callbacks[i];
                        action();
                    }
                }
            });
            dicBtnAction.Add(btn, actionList);
        }
    }

    public static void RemoveClickListener(Button btn,Action callback)
    {
        if (dicBtnAction.ContainsKey(btn))
        {
            List<Action> actioList = dicBtnAction[btn];
            actioList.Remove(callback);
            if(actioList.Count == 0)
            {
                actioList.Clear();
                actioList = null;
                dicBtnAction.Remove(btn);
                btn.onClick.RemoveAllListeners();
            }
        }
    }



	
}
